from django.contrib import auth
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from django import forms

from post.forms import RegisterForm

#注册===================================================================
def register(request):
    if request.method=="GET":  #显示登录页面
        return render(request,"register.html")
    if request.method=="POST":#输入完用户名和密码后提交
        forms=RegisterForm(request.POST)
        # 验证
        if forms.is_valid():#通过验证
            data=forms.cleaned_data;
            user=User.objects.create_user(username=data["username"],
                                          password=data["password"],
                                          email=data["email"])
        #     register=forms.save(commit=False)#控制提交
        #     register.is_active=1 #设置激活用户
        #     register.password=make_password(forms.cleaned_data["password"]) #加密使用make_password函数
        #     register.save() #提交数据
        # #     设置seeson
        #     request.session["username"]=forms.cleaned_data['username']
            return render(request,"base.html")
            # return redirect(reverse("home"))
        # return redirect('/index/')
        else:
        #     验证失败
            return render(request,"register.html",{"forms":forms})

        # 登录
class LoginForm(forms.Form):
    username = forms.CharField(label="昵称",
                               error_messages={"required": "请输入邮箱或昵称"})
    password = forms.CharField(label="密码",
                               error_messages={"required": "请输入密码"})

        # 登录=========================================================================
class LoginView(View):
    def get(self,request):
        return render(request,"log.html")
    def post(self,request):
        loginForm=LoginForm(request.POST)
        if loginForm.is_valid()==False:
            return render(request,"log.html",{"forms""loginForm"})
        user_name=loginForm.cleaned_data["username"]
        password=loginForm.cleaned_data["password"]
        if user_name.find("@")>0:     #用户输入的为邮箱
            user_obj=User.objects.filter(email=user_name)
            if len(user_obj)>0:
                user_name=user_obj[0].username
        user=auth.authenticate(username=user_name,password=password)
        if user:
            request.session["username"]=user_name
            return redirect("home")
        else:

            return render(request,"log.html",{"error":"用户名或密码错误"})

# 退出登录=============================================================================
def quit(request):
    del request.session["username"]
    return  redirect(reverse("home"))